<?php
namespace app\spadmin\controller\auth;
use app\common\controller\Backend;
use Exception;
use think\Config;
use think\Db;
use think\helper\Hash;

class Admin extends Backend{

    public function _initialize()
    {
        parent::_initialize();
        $this->model = model('Admin');
        $this->assign('auth_group',$this->auth->getGroupContentX());

        
    }

    public function index(){

        $this->request->filter(['strip_tags', 'trim']);
        if($this->request->isAjax()){
            $data = $this->request->param();
            if (isset($data['keywords']) && $data['keywords']) {
                $map['username|mobile'] = ['like', '%' . $data['keywords'] . '%'];
            }
            if (isset($data['last_login_ip']) && $data['last_login_ip']) {
                $map['last_login_ip'] = ['like', '%' . $data['last_login_ip'] . '%'];
            }
            if (isset($data['start_date']) && $data['start_date']) {
                $map['last_login_time'] = [ 'BETWEEN', [$data['start_date'], $data['end_date']]];
            }
            if (isset($data['status']) && $data['status']) {
                $map['status'] = $data['status'];
            } else {
                $map['status'] = 1;
            }
            $groupaccess = model('AuthGroupAccess')->alias('a')->join('__AUTH_GROUP__ g','g.id = a.group_id')->field('admin_id,group_id,g.name')->select();
            $group = [];
            foreach ($groupaccess as $key => $value) {
                $group[$value['admin_id']][] = $value['name'];
            }
            $list =   model('Admin')->where($map)->paginate($data['limit'])->toArray();
            foreach ($list['data'] as $key => $value) {
                $list['data'][$key]['group'] = $group[$value['id']]?implode(',',$group[$value['id']]):'';
            }
            return $this->result($list);
        }
        return $this->view->fetch();
    }

    public function personal(){
        $row = $this->model->get(['id'=>$this->auth->id]);
        if($this->request->isPost()){
            $data = $this->request->post('',[],'strip_tags');
            if($data['password']){
                $data['repassword'] || $this->error('要修改密码，确认密码必须填写');
                if($data['password'] !== $data['repassword']){
                    $this->error('密码必须和确认密码一致');
                }
                $data['password'] = md5(md5($data['password']) . Config::get('auth_key'));
            }else{
                unset($data['password']);
            }
            $result = $row->validate()->allowField(true)->save($data,$data['id']);
            if($result === false){
                $this->error($row->getError());
            }
            $this->success('操作成功');
        }
        $this->assign('info',$row);
        return $this->view->fetch();
    }
    public function add(){
        if($this->request->isPost()){
            $data = $this->request->post('',[],'strip_tags');
            if(empty($data['password'])){
                $this->error('密码必须填写');
            }
            if(empty($data['repassword'])){
                $this->error('确认密码必须填写');
            }
            if($data['password'] !== $data['repassword']){
                $this->error('密码必须和确认密码一致');
            }
            if($data['group'] == ''){
                $this->error('请选择角色权限');
            }
            $data['password'] = md5(md5($data['password']) . Config::get('auth_key'));
            Db::startTrans();
            try {
                $result = $this->model->validate()->allowField(true)->save($data);
                if($result === false){
                    Exception($this->model->getError());
                }
                $dataset = [];
                foreach (explode(',',$data['group']) as $value) {
                    $dataset[] = ['admin_id' => $this->model->id, 'group_id' => $value];
                }
                model('AuthGroupAccess')->saveAll($dataset);
                Db::commit();
            } catch (\think\exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            
            $this->success('操作成功');
        }
        return $this->view->fetch();
    }
    public function edit($ids=null){
        $row = $this->model->get(['id'=>$ids]);
        if($this->request->isPost()){
            $data = $this->request->post('',[],'strip_tags');
            if($data['password']){
                 $data['repassword'] || $this->error('要修改密码，确认密码必须填写');
                 if($data['password'] !== $data['repassword']){
                    $this->error('密码必须和确认密码一致');
                 }
                 $data['password'] = md5(md5($data['password']) . Config::get('auth_key'));
            }else{
                unset($data['password']);
            }
            Db::startTrans();
            try {
                $result = $this->model->validate()->allowField(true)->save($data,$data['id']);
                if($result === false){
                    Exception($this->model->getError());
                }
                model('AuthGroupAccess')->where('admin_id', $this->model->id)->delete();
                $dataset = [];
                foreach (explode(',',$data['group']) as $value) {
                    $dataset[] = ['admin_id' => $this->model->id, 'group_id' => $value];
                }
                model('AuthGroupAccess')->saveAll($dataset);
                Db::commit();
            } catch (\think\exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            $this->success('操作成功');
        }
        $row['group'] = model('AuthGroupAccess')->where('admin_id',$row['id'])->column('group_id');
        $this->assign('info',$row);
        return $this->view->fetch();
    }

}